const DB = uniCloud.database();
const DBCmd = DB.command;
const $ = DB.command.aggregate;
let dbJQL = null
//当前登录用户id
let uid
const uniID = require('uni-id-common')
const options = require('./options.js')

module.exports = {
	_before: async function () { // 通用预处理器
		//客户端信息
		const clientInfo = this.getClientInfo()
		//云服务信息
		const cloudInfo = this.getCloudInfo()
		//token信息
		const token = this.getUniIdToken()
		dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云对象的clientInfo
			clientInfo
		})
		if(token) {
			const tokenRes  = await uniID.createInstance({
				clientInfo
			}).checkToken(token)
			
			if(tokenRes.uid) {
				uid = tokenRes.uid
			}
		}
	},
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	
	async getIndexCustomer(params) {
		// 参数校验，如无参数则不需要
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		if (!uid) {
			return {
				status:true,
				msg:'查询成功',
				data:null
			}
		}
		let {page,limit,...where}=params
		let myLevelRes=await dbJQL.collection('mydb-permission').where({user_id:uid}).field('type').get()
	
		let myLevelUserRes=await dbJQL.collection('mydb-permission, uni-id-users').where({parent_id:uid}).field('type,user_id.nickname,parent_id.nickname').get()
		console.log('myLevelUserRes',myLevelUserRes)
	
		let myLevel=myLevelRes.data[0] ?  myLevelRes.data[0]['type'] : 1  // 业务员: 1,团队长:2,管理员: 3,超级管理员: 4
		let myLevelUsers=myLevelUserRes.data && myLevelUserRes.data.length ? myLevelUserRes.data.map((item)=>item.user_id) : []
		myLevelUsers=[...myLevelUsers,uid]
		switch (myLevel){
			case 1:
				where.associated_users=uid
				break;
			case 2:
				where.associated_users=DBCmd.in(myLevelUsers)
				break;
			case 3:
				where.is_public=true
				break;
			default:
				where.is_public=true
				break;
		}
		
		console.log('where',where)

		// 业务逻辑
		let res=await dbJQL.collection('mydb-customer').where({...where}).field('birthday,debt_info,name,type,source,phone,create_date,is_public,status').orderBy('create_time', 'desc')
					.skip((page - 1) * limit)
					.limit(limit)
					.get()
		let favorites=await dbJQL.collection('mydb-customer-favorite').where({user_id:uid}).field('customer_id').get()
		// 返回结果
		res.data.forEach((item)=>{
			item.creator='李**'
		})
		return {
			status:true,
			msg:'查询成功',
			favorites:favorites.data,
			data:res.data //请根据实际需要返回值
		}
	},
	async getCustomerDetail(_id){
		// 业务逻辑
		const res =await dbJQL.collection('mydb-customer,uni-id-users').where({_id}).field('associated_users{username,nickname},birthday,debt_info,name,type,source,phone,status,phone').get() 
		const data = res.data[0]
		const types=options.typeOptions
		const detailInfo={
			...data,
			type:types.find((item)=>item.value==data.type)?.text || '未知',

		}
		return {
			status:true,
			msg:'查询成功',
			data:detailInfo //请根据实际需要返回值
		}
	},
	// 客户提交需求保存
	async saveCustomer(params){
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '内容不能为空'
			}
		}
		let result=await dbJQL.collection('mydb-customer').add(params)
		return {
			status:true,
			msg:'保存成功',
			result 
		}
	},
	// 收藏客户
	async favoriteCustomer(params){
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '客户不能为空'
			}
		}
		let result=await dbJQL.collection('mydb-customer-favorite').add({
			user_id:uid,
			customer_id:params._id
		})
		return {
			status:true,
			msg:'收藏成功',
			result 
		}
	},
	async getCenterCount(){
		return {
			status:true,
			msg:'获取成功',
			result:{
				...options.userOptions
			}
		}
	},
	async getOptions(){
		return  options
	},
	async getHomeData(){
		return {
			menus: [
			  { name: '产品', icon: 'color', path: '/pages/product/product' },
			  { name: '客户', icon: 'personadd', path: '/pages/index/index' },
			  { name: '人事', icon: 'auth', path: '/pages/organize/organize' },
			  { name: '商学院', icon: 'shop', path: '/pages/videos/videos?category_id=68ec70083d029c7eaa728cdd&title=人事管理' },
			  { name: '网点', icon: 'location', path: '/pages/stations/stations' },
			  { name: '加盟', icon: 'fire', path: '/pages/invest/invest' }
			]
		}
	}
	
}
